#include "getpidpackage.h"

GetPidPackage::GetPidPackage()
{

}
GetPidPackage::~GetPidPackage()
{
}

GetPidPackage &GetPidPackage::get_instance()
{
    static GetPidPackage instance;
    return instance;
}

void GetPidPackage::ParseTS_PackageHead(TS_PACKAGE_HEAD *pstTS_PackageHead, unsigned char *pucPackageBuffer)
{
    pstTS_PackageHead->sync_byte = pucPackageBuffer[0];
    pstTS_PackageHead->transport_error_indicator = pucPackageBuffer[1] >> 7;
    pstTS_PackageHead->payload_unit_start_indicator = (pucPackageBuffer[1] >> 6) & 0x01;
    pstTS_PackageHead->transport_priority = (pucPackageBuffer[1] >> 5) & 0x01;
    pstTS_PackageHead->PID = ((pucPackageBuffer[1] & 0x1F) << 8) | pucPackageBuffer[2];
    pstTS_PackageHead->transport_scrambling_control = pucPackageBuffer[3] >> 6;
    pstTS_PackageHead->adaption_field_control = (pucPackageBuffer[3] >> 4) & 0x03;
    pstTS_PackageHead->continuity_counter = pucPackageBuffer[3] & 0x0f;
}

int GetPidPackage::IsWantPid(unsigned int *puiWantPID, unsigned int uiPID)
{
    int iLoopTime = 0;
    int iNumber = puiWantPID[0];

    for (iLoopTime = 1; iLoopTime <= iNumber; iLoopTime++)
    {
        if (puiWantPID[iLoopTime] == uiPID)
        {
            return 1;
        }
    }
    return 0;
}

int GetPidPackage::SavePID_Packege(FILE *pfTsFile, int iTsPosition, int iTsLength, unsigned int *puiWantPID, FILE *pfSaveFile)
{
    unsigned char aucPackageBuffer[PACKAGE_MAX_LENGTH] = {0};
    TS_PACKAGE_HEAD stTS_PackageHead = {0};

    if (-1 == fseek(pfTsFile, iTsPosition, SEEK_SET))
    {
        return -1;
    }
    while (!feof(pfTsFile))
    {
        if ((sizeof(char) * iTsLength) != fread((unsigned char *)aucPackageBuffer, sizeof(char), iTsLength, pfTsFile))
        {
            return 0;
        }
        ParseTS_PackageHead(&stTS_PackageHead, aucPackageBuffer);
        if (0x47 != stTS_PackageHead.sync_byte)
        {
            continue;
        }
        if (1 == IsWantPid(puiWantPID, stTS_PackageHead.PID))
        {
            if ((sizeof(char) * iTsLength) != fwrite((unsigned char *)aucPackageBuffer, sizeof(char), iTsLength, pfSaveFile))
            {
                return -1;
            }
        }
    }
    return 0;
}
